﻿using System;
using System.Windows;
using System.Windows.Threading;
using MyFramework.Helpers;
using MyFramework.Shell.ViewModels;

namespace MyFramework.Shell
{
    /// <summary>
    /// My application
    /// </summary>
    public abstract class MyApplication : Application
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MyApplication"/> class.
        /// </summary>
        public MyApplication()
        {
            this.Startup += new StartupEventHandler(MyApplication_Startup);
            this.Dispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(OnDispatcherUnhandledException);
        }

        /// <summary>
        /// Handles the Startup event of the MyApplication control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="StartupEventArgs"/> instance containing the event data.</param>
        protected virtual void MyApplication_Startup(object sender, StartupEventArgs e)
        {
            var bootstrapper = GetBootstrapper();
            bootstrapper.Run();
        }

        /// <summary>
        /// Gets the bootstrapper.
        /// </summary>
        /// <returns></returns>
        protected abstract MyBootstrapper GetBootstrapper();

        /// <summary>
        /// Called when [dispatcher unhandled exception].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Threading.DispatcherUnhandledExceptionEventArgs"/> instance containing the event data.</param>
        protected virtual void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {

            try
            {

                var excptionViewModel = new ExceptionHandlingViewModel(e.Exception, ScreenshotHelper.GetJpgImage(Application.Current.MainWindow, 1, 90));
                var window = excptionViewModel.Views.MainView;
                ((Window)window).ShowDialog();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, e1.StackTrace, MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
    }
}
